# coding:utf-8
import pandas as pd
from xtquant import xtdata, xtconstant, xttrader
from Config import *
from datetime import datetime

pd.set_option('display.max_columns', None)  
pd.set_option('display.width', 1000)        
pd.set_option('display.max_rows', None)
pd.set_option('display.max_colwidth', 50)
# 设置股票池，例：'000000.SZ', '600000.SH'
code_list = ['000712.SZ']
# 逐个下载历史数据
for code in code_list:
    xtdata.download_history_data(code, period='1d', start_time='20240731')
# 获取前一天的volume
volume_data = xtdata.get_market_data(['volume'], code_list, period='1d', count=1)
# 注意一下收盘价的日期
print(volume_data)

# 用于跟踪已下单股票的字典
ordered_stocks = {}
# 最大下单数量
max_order_count = 2
# 下单计数器
order_count = 0

# 单股买入资金
fund = 5000


def callback_func(data):

    global order_count  # 使用全局变量

    # 转换为DataFrame
    df = pd.DataFrame(data).T

    # 时间戳转换函数
    def timestamp_to_time(timestamp):
        return datetime.fromtimestamp(timestamp / 1000).strftime('%H:%M:%S')

    # 时间戳转换为小时分钟秒
    df['time'] = df['time'].apply(timestamp_to_time)

    # 精简数据，并提取'askVol'中的第一个值
    df = df[['time', 'lastPrice', 'lastClose', 'askVol']].assign(askVol=df['askVol'].apply(lambda x: x[0]))

    # 将获取的volume数据整合到DataFrame中
    volume_df = pd.DataFrame(volume_data['volume'].values, index=volume_data['volume'].index, columns=['Volume'])
    df = pd.concat([df, volume_df], axis=1)
    print(df)

    # 创建一个时间范围的条件。竞价，上证票3秒一跳但不整齐，倒数第二笔有57，58,59。深证票9秒一跳，倒数第二笔都是57。
    time_condition = (df['time'] >= '09:24:57') & (df['time'] <= '09:25:03')
    # time_condition = (df['time'] >= '15:00:00') & (df['time'] <= '15:00:05') # 测试用

    # 创建一个价格条件，0%到5%开盘。
    price_condition = (df['lastPrice'] <= df['lastClose'] * 1.04) & (df['lastPrice'] > df['lastClose'] * 1)
    # price_condition = (df['lastPrice'] <= df['lastClose'] * 9.98) & (df['lastPrice'] >= df['lastClose'] * 0.01) # 测试用

    # 创建一个成交量条件，askVol大于等于volume的3%
    volume_condition = df['askVol'] >= df['Volume'] * 0.03

    # 将三个条件合并
    final_condition = time_condition & price_condition & volume_condition

    # 根据条件筛选 DataFrame
    filtered_df = df[final_condition]

    # 符合条件的股票执行下单
    for stock_code in filtered_df.index:
        # 检查是否已下单，如果已下单或达到最大下单数量则跳过
        if stock_code in ordered_stocks or order_count >= max_order_count:
            continue

        # 计算买入价格，2%价格。实践中59秒识别到，等下单成功25分01秒了，集合竞价没有价格笼子，但是集合竞价后有2%为防止价格超出价格笼子。
        adjusted_price = round(filtered_df.loc[stock_code, 'lastPrice'] * 1.02, 2)
        # 计算股数
        stock_quantity = fund / adjusted_price  # 符合条件的50000配置
        stock_quantity -= stock_quantity % 100  # 取整百
        stock_quantity = int(stock_quantity)  # 将结果转换为整数

        # 获取时间
        time = filtered_df.loc[stock_code, 'time']
        # 下单
        fix_result_order_id = xt_trader.order_stock(account_putong, stock_code, xtconstant.STOCK_BUY, stock_quantity,
                                                    xtconstant.FIX_PRICE, adjusted_price, '首板弱转强', '买入')


        print(f"时间：{time}，已下单股票：{stock_code}，订单号：{fix_result_order_id}")

        # 将已下单股票加入字典
        ordered_stocks[stock_code] = True
        # 更新下单计数器
        order_count += 1

xtdata.subscribe_whole_quote(code_list, callback=callback_func)
xtdata.run()
